package com.gt.controller.security;

import com.gt.entity.security.*;
import com.gt.entity.user.User;
import com.gt.service.security.LoginService;
import com.gt.service.user.UserService;
import com.gt.utils.TokenUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @version V1.0.0
 * @Description 登陆接口
 * @Author liuyuequn weanyq@gmail.com
 * @Date 2017/10/3 1:30
 */
@RestController
public class TokenController {

    private final LoginService loginService;

    @Autowired
    private UserService userService;

    @Value("${token.header}")
    private String tokenHeader;

    @Autowired
    private TokenUtils tokenUtils;

    @Autowired
    public TokenController(LoginService loginService) {
        this.loginService = loginService;
    }

    @RequestMapping(value = "/getToken",method = RequestMethod.POST)
    public ResultMap getToken(@Valid RequestLoginUser requestLoginUser, BindingResult bindingResult){
        // 检查有没有输入用户名密码和格式对不对
        if (bindingResult.hasErrors()){
            return new ResultMap().fail("400").message("缺少参数或者参数格式不对").data("");
        }
        LoginDetail loginDetail = loginService.getLoginDetail(requestLoginUser.getUsername());
        ResultMap ifLoginFail = checkAccount(requestLoginUser, loginDetail);
        if (ifLoginFail != null){
            return ifLoginFail;
        }
        String token = loginService.generateToken((TokenDetail) loginDetail);
        new Thread(() -> {
            User query = new User();
            query.setUserName(loginDetail.getUsername());
            query.setPassword(loginDetail.getPassword());
            List<User> queryList = this.userService.queryList(query);
            if(null != queryList && !queryList.isEmpty()){
                User edit = new User();
                edit.setId(queryList.get(0).getId());
                edit.setLastLoginTime(System.currentTimeMillis());
                this.userService.edit(edit);
            }
        }).start();
        return new ResultMap().success().message("获取成功").data(new Data().addObj(tokenHeader,token));
    }

    private ResultMap checkAccount(RequestLoginUser requestLoginUser, LoginDetail loginDetail){
        if (loginDetail == null){
            return new ResultMap().fail("434").message("账号不存在！").data("");
        }else {
            if (loginDetail.enable() == false){
                return new ResultMap().fail("452").message("账号在黑名单中").data("");
            }
            if (!loginDetail.getPassword().equals(requestLoginUser.getPassword())){
                return new ResultMap().fail("438").message("密码错误！").data("");
            }
        }
        return null;
    }

    /**
     * 检验token是否可用
     * @param access_token
     * @return
     */
    @PostMapping("/chkToken")
    @ResponseBody
    public boolean chkToken(@RequestParam(required = true, value = "access_token") String access_token){
        boolean flag = StringUtils.isEmpty(tokenUtils.getUsernameFromToken(access_token))?false:true;
        return flag;
    }

}
